from typing import Union

import requests
import urllib3

from requests.auth import HTTPBasicAuth

urllib3.disable_warnings()


class Http(object):
    UA_CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0)' \
                ' AppleWebKit/535.11 (KHTML, like Gecko)' \
                ' Chrome/17.0.963.56 Safari/535.11'

    HEADERS = {
        "User-Agent": UA_CHROME
    }

    DOWNLOAD_BUFFER_SIZE = 512 * 1024

    mServer: str
    mAuth: HTTPBasicAuth

    def __init__(self, server: str, username: str = None, password: str = None):
        self.mServer = server
        self.mAuth = HTTPBasicAuth(username, password)

    def get(self, url: str, on_receive=None) -> Union[bytes, None]:
        response = requests.get(url, verify=False, auth=self.mAuth, stream=True, headers=self.HEADERS)
        if 'content-length' in response.headers:
            file_size = response.headers['content-length'].strip()
            if file_size == '':
                file_size = -1
            else:
                file_size = int(file_size)
        else:
            file_size = -1  # size unknown

        if on_receive is None:
            content: bytes = b''
            for chunk in response.iter_content(self.DOWNLOAD_BUFFER_SIZE):
                content += chunk
            return content
        else:
            # update progress for start
            size_downloaded: int = 0
            on_receive(size_downloaded, file_size, b'')

            # do download
            for chunk in response.iter_content(self.DOWNLOAD_BUFFER_SIZE):
                size_downloaded += len(chunk)
                on_receive(size_downloaded, file_size, chunk)

            # update progress for finished
            on_receive(size_downloaded, file_size, b'')
            return None  # receive from on_receive
